package com.example.mypplication.component

import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.ViewCompat

class StickyViewBehavior(context: Context, attrs: AttributeSet) :
    CoordinatorLayout.Behavior<View>(context, attrs) {

    private var initialY = 0f
    private var isSticky = false
    private var stickyY = 0f

    override fun onLayoutChild(
        parent: CoordinatorLayout,
        child: View,
        layoutDirection: Int
    ): Boolean {
        initialY = child.y
        stickyY = 0f // 吸顶位置设为顶部
        return super.onLayoutChild(parent, child, layoutDirection)
    }

    override fun onStartNestedScroll(
        coordinatorLayout: CoordinatorLayout,
        child: View,
        directTargetChild: View,
        target: View,
        axes: Int,
        type: Int
    ): Boolean {
        return axes == ViewCompat.SCROLL_AXIS_VERTICAL
    }

    override fun onNestedPreScroll(
        coordinatorLayout: CoordinatorLayout,
        child: View,
        target: View,
        dx: Int,
        dy: Int,
        consumed: IntArray,
        type: Int
    ) {
        // 检查是否应该进入吸顶状态
        if (!isSticky && child.y <= stickyY && dy > 0) {
            isSticky = true
        }

        // 检查是否应该退出吸顶状态
        if (isSticky && dy < 0 && target.canScrollVertically(-1)) {
            isSticky = false
        }

        if (isSticky) {
            // 吸顶状态下保持位置不变
            child.y = stickyY
            return
        }

        // 非吸顶状态下的正常滑动
        if (dy > 0) { // 上滑
            val newY = child.y - dy
            if (newY > stickyY) {
                child.y = newY
                consumed[1] = dy
            } else {
                child.y = stickyY
                consumed[1] = (child.y - stickyY).toInt()
                isSticky = true
            }
        } else if (dy < 0) { // 下滑
            val newY = child.y - dy
            if (newY < initialY) {
                child.y = newY
                consumed[1] = dy
            } else {
                child.y = initialY
                consumed[1] = (initialY - child.y).toInt()
            }
        }
    }
}